const R = require('../utils/R')
const { tokenGenerator } = require('../utils/token')
const userService = require('../service/user.service')
const { LOGIN_EXCEPTION, REGISTER_EXCEPTION, GET_INFO_EXCEPTION } = require('../error/errorType')

class UserController {
  // 用户登录
  async login (ctx, next) {
    try {
      // 具体代码
      const { userInfo } = ctx
      let id = userInfo.id
      let name = userInfo.name
      const token = tokenGenerator({ id, name })
      ctx.dto = R.ok('用户登录成功', {
        id: userInfo.id,
        name: userInfo.name,
        token: `Bearer ${token}`
      })
    } catch (err) {
      console.log(err.message)
      return ctx.app.emit('error', new Error(LOGIN_EXCEPTION), ctx)
    }
    await next()
  }

  // 用户注册
  async register (ctx, next) {
    try {
      const { name, password } = ctx.request.body
      console.log(name, password)
      await userService.register(name, password)
      ctx.dto = R.ok('用户注册成功', name)
    } catch (err) {
      console.log(err.message)
      return ctx.app.emit('error', new Error(REGISTER_EXCEPTION), ctx)
    }
    await next()
  }

  // 获取个人信息
  async getInfo (ctx, next) {
    try {
      const { userInfo } = ctx
      console.log();
      const result = await userService.getUserInfoByName(userInfo.name)
      delete result[0].password
      console.log(result);
      ctx.dto = R.ok('用户获取个人信息成功', result)

      // ctx.dto = R.ok('获取个人信息测试成功', null)
    } catch (err) {
      console.log(err.message)
      return ctx.app.emit('error', new Error(GET_INFO_EXCEPTION), ctx)
    }
    await next()
  }
}

module.exports = new UserController()